<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/bootstrap-table.min.css">
    <link rel="stylesheet" href="/css/jquery-confirm.min.css">
    <link rel="stylesheet" href="/css/pub.css">
    <link rel="stylesheet" href="/css/order.css">
    <link rel="stylesheet" href="/css/font-awesome-all.min.css">
    <style>
        .test-param-group {
            display: flex;
            padding-left: 15px;
            border: 1px solid lightgray;
            padding-top: 10px;
        }

        .test-param-group .form-check {
            margin-left: 16px;
        }

        .test-param-group .text-primary {
            width: 80px;
        }

        .modal-content {
            width: 700px;
        }

        .cal-type-body {
            min-height: 400px;
            max-height: 600px;
        }

        .zone-stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        .zone-stats-child {
            display: flex;
        }

        .zone-stats-child .zone-title {
            margin-right: 8px;
        }

        .zone-stats-child .zone-count {
            font-weight: bold;
            color: red;
            font-size: 18px;
        }

        #zoneList {
            font-weight: bold;
        }

        #zoneList option {
            color: blue;
            height: 20px;
        }


        #totalCount {
            border: none;
            font-size: 20px;
            font-weight: bold;
            color: darkgreen;
        }
    </style>
</head>

<body>
    <div class="sync-area mt-3">
        <div class="row">
            <div class="col-md-6">
                <h5>发送订单到阿耳忒弥斯</h5>
                <button class="btn btn-primary mb-3" id="startMqttBtn" onclick="onClickStartMqtt()"><i class="fa-solid fa-share-nodes"></i>发送</button>
                <button class="btn btn-danger mb-3" id="releaseLockBtn" onclick="onClickReleaseLock()"><i class="fa-solid fa-unlock"></i>释放锁</button>
                <button class="btn btn-primary mb-3" id="restartWebsocket" disabled
                    onclick="onClickRestartWebsocket()"><i class="fa-solid fa-plug"></i>重连Socket</button>
                <div class="message-container  ws-messages p-3 border rounded">
                    <div id="wsMessages" class="message-body"></div>
                </div>
            </div>
            <div class="col-md-6">
                <h5>接收阿耳忒弥斯订单并汇总(加盐分压)</h5>
                <button class="btn btn-success mb-3 ms-2" id="startMqttSinkBtn"
                    onclick="startWebSocketSink()"><i class="fa-solid fa-circle-play"></i>启动计算</button>
                <button class="btn btn-danger mb-3 ms-2" id="stopMqttSinkBtn" disabled
                    onclick="stopWebSocketSink()"><i class="fa-solid fa-circle-stop"></i>停止计算</button>
                <!-- <button class="btn btn-info mb-3 ms-2" id="querySinkTarget" onclick="querySinkTarget()">查询目标表</button> -->
                <div class="message-container p-3 border rounded">
                    <div id="flinkOutput" class="message-body" style="display:block;"></div>
                    <div id="echartOutput" class="message-body" style="display:none; height:400px;"></div>
                    <div id="zoneStats" class="zone-stats mt-3" style="display:none;">
                        <div class="zone-stats-grid"></div>
                        <div>
                            <label>汇总:</label><input id="totalCount" type="text" disabled="disabled">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-12">
                <button class="btn btn-warning" id="clearMessagesBtn" onclick="onClickClearMessages()">
                    <i class="fas fa-trash-alt"></i> 清除消息
                </button>
            </div>
        </div>
    </div>

    <!-- 计算方式选择模态框 -->
    <div class="modal fade" id="calculationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">选择计算方式和分组方式</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>
                <div class="modal-body cal-type-body  ">
                    <div class="mb-4 test-param-group">
                        <h6 class="mb-3 text-primary">分组方式</h6>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="grpType" id="grpTypeSex" value="性别"
                                checked>
                            <label class="form-check-label" for="grpTypeSex">按性别</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="grpType" id="grpTypeRegion" value="区域">
                            <label class="form-check-label" for="grpTypeRegion">按地区</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="grpType" id="grpTypeMixed" value="区域+性别">
                            <label class="form-check-label" for="grpTypeMixed">地区+性别</label>
                        </div>
                    </div>

                    <div class="mb-4 test-param-group">
                        <h6 class="mb-3 text-primary">计算窗口</h6>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="calculationType" id="calcTypeSlide"
                                value="滑动窗口" checked>
                            <label class="form-check-label" for="calcTypeSlide">滑动</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="calculationType" id="calcTypeTumbling"
                                value="滚动窗口" checked>
                            <label class="form-check-label" for="calcTypeTumbling">滚动处理时间</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="calculationType"
                                id="calcTypeTumblingEventTime" value="滚动事件时间窗口" checked>
                            <label class="form-check-label" for="calcTypeTumblingEventTime">滚动事件时间</label>
                        </div>
                        <br />
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="calculationType" id="calcTypeGlobal"
                                value="全局窗口">
                            <label class="form-check-label" for="calcTypeGlobal">全局</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="calculationType" id="calcTypeNone"
                                value="无窗口">
                            <label class="form-check-label" for="calcTypeNone">无</label>
                        </div>
                    </div>



                    <!-- 滑动窗口参数 -->
                    <div id="slideWindowParams" class="params-section p-3 bg-light rounded" style="display: block;">
                        <h6 class="mb-3 text-primary">滑动窗口参数</h6>
                        <div class="mb-3">
                            <label for="winLen" class="form-label">窗口长度(秒)</label>
                            <input type="number" class="form-control" id="winLen" min="1" value="1">
                        </div>
                        <div class="mb-3">
                            <label for="winInterval" class="form-label">窗口间隔(毫秒)</label>
                            <input type="number" class="form-control" id="winInterval" min="100" value="500">
                        </div>
                    </div>

                    <!-- 滚动窗口参数 -->
                    <div id="tumblingWindowParams" class="params-section p-3 bg-light rounded" style="display: none;">
                        <h6 class="mb-3 text-primary">滚动窗口参数</h6>
                        <div class="mb-3">
                            <label for="winLenTumbing" class="form-label">窗口长度(秒)</label>
                            <input type="number" class="form-control" id="winLenTumbing" min="1" value="1">
                        </div>
                    </div>

                    <!-- 全局窗口参数 -->
                    <div id="globalWindowParams" class="params-section p-3 bg-light rounded" style="display:none;">
                        <h6 class="mb-3 text-primary">全局窗口参数</h6>
                        <div class="mb-3 test-param-group">
                            <label class="form-label">触发器类型</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="triggerType" id="triggerTypeCount"
                                    value="计数触发器" checked>
                                <label class="form-check-label" for="triggerTypeCount">计数触发器</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="triggerType" id="triggerTypeTime"
                                    value="周期性触发器">
                                <label class="form-check-label" for="triggerTypeTime">周期性触发器</label>
                            </div>
                            <!-- 特定秒数后停止触发器 -->
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="triggerType" id="triggerTypeStop"
                                    value="特定秒数后停止触发器">
                                <label class="form-check-label" for="triggerTypeStop">特定秒数后停止触发器</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="triggerVal" class="form-label">触发器值(条记录数)</label>
                            <input type="number" class="form-control" id="triggerVal" min="1" value="10">
                        </div>
                        <!-- 重复间隔，仅当触发器类型为 周期性触发器、特定秒数后停止触发器 的时候才显示  -->
                        <div class="mb-3 repeat-interval">
                            <label for="repeatInterval" class="form-label">重复间隔(毫秒)</label>
                            <input type="number" class="form-control" id="repeatInterval" min="1" value="50">
                        </div>
                    </div>

                    <!-- 无窗口参数 -->
                    <div id="noWindowParams" class="params-section p-3 bg-light rounded" style="display: none;">
                        <image src="/image/夏天.png" style="width: 300px; height: 200px;" />
                        <div style="width: 10px;margin-left: 67px;font-size: 16px;font-weight: bold;">没有参数需要输入</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmCalculation"
                        onclick="onClickConfirmCalculation()">确定</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 同步数量输入模态框 -->
    <div class="modal fade" id="syncCountModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">输入发送信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="syncCount" class="form-label">请输入发送订单页数</label>
                        <input type="number" class="form-control" id="syncCount" min="1" value="1">
                    </div>
                    <div class="mb-3">
                        <label for="pageSize" class="form-label">每页记录数</label>
                        <input type="number" class="form-control" id="pageSize" min="1" value="10">
                    </div>
                    <div class="mb-3">
                        <label for="zoneInput" class="form-label">区域名称</label>
                        <input type="text" class="form-control" id="zoneInput" list="zoneList" placeholder="输入或选择区域">
                        <datalist id="zoneList">
                            <option value="北京">
                            <option value="上海">
                            <option value="天津">
                            <option value="重庆">
                            <option value="河北">
                            <option value="山西">
                            <option value="辽宁">
                            <option value="吉林">
                            <option value="黑龙江">
                            <option value="江苏">
                            <option value="浙江">
                            <option value="安徽">
                            <option value="福建">
                            <option value="江西">
                            <option value="山东">
                            <option value="河南">
                            <option value="湖北">
                            <option value="湖南">
                            <option value="广东">
                            <option value="海南">
                            <option value="四川">
                            <option value="贵州">
                            <option value="云南">
                            <option value="陕西">
                            <option value="甘肃">
                            <option value="青海">
                            <option value="台湾">
                            <option value="内蒙古">
                            <option value="广西">
                            <option value="西藏">
                            <option value="宁夏">
                            <option value="新疆">
                            <option value="香港">
                            <option value="澳门">
                        </datalist>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="sendSocket">
                        <label class="form-check-label" for="sendSocket">是否发送WebSocket消息</label>
                    </div>
                    <div class="mb-3">
                        <label for="interval" class="form-label">发送间隔(毫秒)</label>
                        <input type="number" class="form-control" id="interval" min="300" value="500"
                            placeholder="不要输入太大间隔，否则可能会等待过久">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmSync"
                        onclick="onClickConfirmSync()">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>

<script src="/js/jquery-3.7.1.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/bootstrap-table.min.js"></script>
<script src="/js/jquery-confirm.min.js"></script>
<script src="/js/pub.js"></script>
<script src="/js/task.js"></script>
<script src="/js/order.js"></script>
<script src="/js/echarts.min.js"></script>
<script src="/js/mqtt.js"></script>
<script src="/js/font-awesome-all.min.js" data-auto-replace-svg="nest"></script>
<script>
    // WebSocket连接
    function initWebSocket() {
        if (!window.torder) {
            window.torder = {};
        }
        if (window.torder.wsUri === undefined || window.torder.wsUri === null) {
            window.torder.wsUri = getWebsocketUri();
        }
        if (window.torder.Websocket == undefined || window.torder.Websocket == null) {
            window.torder.websocket = null;
        }
        if (window.torder.websocket != undefined && window.torder.websocket != null) {
            console.log("WebSocket已存在，无需初始化");
            return;
        }
        console.log("初始化websocket连接");
        let websocket = new WebSocket(window.torder.wsUri);
        websocket.onopen = function (evt) {
            addMessageToWebsocketOut("WebSocket连接已建立");
            //发送消息给服务器，告诉自己的名称
            websocket.send("setName:" + FLINK_TEST_FROMMQTT_PARTITION);
        };
        websocket.onclose = function (evt) {
            if (window.torder.websocket != null) {
                //关闭websocket连接
                window.torder.websocket.close();
                clearInterval(window.torder.websocketHeartbeatInterval);
                window.torder.websocket = null;
                addMessageToWebsocketOut("关闭webSocket");
            }
            // 启用重连按钮
            document.getElementById('restartWebsocket').disabled = false;
        };
        websocket.onmessage = function (evt) {
            let data = JSON.parse(evt.data);
            if (data.stageType === MESSAGE_STAGE_TYPE_JOB_ISFINISHED) {
                //此处必须延迟一秒，否则可能就算是可以重用，也会被另外一个操作覆盖。
                setTimeout(() => {
                    document.getElementById('startMqttBtn').disabled = false;
                }, 1000);
            }

            if (data.receiver == undefined || data.receiver == "") {
                addMessageToWebsocketOut(data.data);
            }
            else {
                if (data.dataIsObject) {
                    const grpType = $('input[name="grpType"]:checked').val();
                    const calcType = $('input[name="calculationType"]:checked').val();
                    const triggerType = $('input[name="triggerType"]:checked').val();

                    if (grpType === '区域' && calcType === '全局窗口' && triggerType === '计数触发器') {
                        updateEchart(data.data);
                        updateZoneStats(data.data);
                    } else {
                        addMessageToFlinkOut(JSON.stringify(data.data));
                    }
                }
                else {
                    addMessageToFlinkOut(data.data);
                }
            }
        };
        websocket.onerror = function (evt) {
            // 启用重连按钮
            addMessageToWebsocketOut("WebSocket错误: " + evt);
            if (window.torder.websocket != null) {
                //关闭websocket连接
                window.torder.websocket.close();
                clearInterval(window.torder.websocketHeartbeatInterval);
                window.torder.websocket = null;
                addMessageToWebsocketOut("关闭webSocket");
            }
            document.getElementById('restartWebsocket').disabled = false;
        };
        window.torder.websocket = websocket;

        // 每5秒发送一次心跳
        window.torder.websocketHeartbeatInterval = setInterval(sendHeartbeat, 5000);

        //充值按钮状态
        document.getElementById('startMqttBtn').disabled = false;
        document.getElementById('restartWebsocket').disabled = true;
    }

    // 重连按钮点击事件
    function onClickRestartWebsocket() {
        initWebSocket();
    }

    // MQTT发送按钮点击事件
    function onClickStartMqtt() {
        const syncModal = new bootstrap.Modal(document.getElementById('syncCountModal'));
        syncModal.show();
    }

    // 确认同步按钮点击事件
    function onClickConfirmSync() {
        const syncCount = document.getElementById('syncCount').value;
        if (!syncCount || syncCount < 1) {
            alert('请输入有效的同步数量');
            return;
        }

        const syncModal = bootstrap.Modal.getInstance(document.getElementById('syncCountModal'));
        syncModal.hide();

        // 这里添加实际的MQTT发送逻辑，使用syncCount作为参数
        const pageSize = document.getElementById('pageSize').value;
        const sendSocket = document.getElementById('sendSocket').checked ? 1 : 0;
        const interval = document.getElementById('interval').value;

        const params = new URLSearchParams();
        params.append('pageQty', syncCount);
        params.append('pageSize', pageSize);
        params.append('sendSocket', sendSocket);
        params.append('interval', interval);
        params.append('testNo', FLINK_TEST_FROMMQTT_PARTITION);

        const zoneName = document.getElementById('zoneInput').value;
        let bp = {};
        if (zoneName.trim() != "") {
            bp.zoneName = zoneName;
        }

        sendToMqtt(params, function () {
            document.getElementById('startMqttBtn').disabled = true;
        }, bp);
    }

    function onClickReleaseLock() {
        releaseLock(function () {
            document.getElementById("startMqttBtn").disabled = false;
        })
    }

    // MQTT Sink按钮点击事件
    function startWebSocketSink() {
        const calcModal = new bootstrap.Modal(document.getElementById('calculationModal'));
        calcModal.show();
    }
    // 停止JDBC Sink按钮点击事件
    function stopWebSocketSink() {
        stopMqttTask(FLINK_TEST_FROMMQTT_PARTITION, function (result) {
            if (result.data) {
                document.getElementById("startMqttSinkBtn").disabled = false;
                document.getElementById("stopMqttSinkBtn").disabled = true;
            }
        });
    }

    // 查询目标表
    function querySinkTarget() {
        fetch('/orders/countTargetOrder', {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                addMessageToFlinkOut("目标表累计收到数据:" + data.data + "条");
            });
    }

    // 发送心跳消息
    function sendHeartbeat() {
        if (window.torder.websocket && window.torder.websocket.readyState === WebSocket.OPEN) {
            window.torder.websocket.send("heartbeat");
        } else {
            console.log("WebSocket未连接，无法发送心跳");
        }
    }

    // 计算方式变更事件
    function onChangeCalculationType() {
        document.querySelectorAll('.params-section').forEach(section => {
            section.style.display = 'none';
        });

        const selectedValue = $('input[name="calculationType"]:checked').val();
        if (selectedValue === '滑动窗口') {
            document.getElementById('slideWindowParams').style.display = 'block';
        }
        else if (selectedValue === '滚动窗口' || selectedValue === '滚动事件时间窗口') {
            document.getElementById('tumblingWindowParams').style.display = 'block';
        }
        else if (selectedValue === '全局窗口') {
            document.getElementById('globalWindowParams').style.display = 'block';
        }
        else {
            document.getElementById('noWindowParams').style.display = 'flex';
        }
    }

    // 初始化时绑定radio的onclick事件
    $(document).ready(function () {
        $('input[name="calculationType"]').each(function () {
            this.onclick = onChangeCalculationType;
        });

        $('input[name="triggerType"]').each(function () {
            this.onclick = onClickTriggerTypeChange;
        });
    });

    //触发器类型变更事件
    function onClickTriggerTypeChange() {
        let triggerType = $('input[name="triggerType"]:checked').val();
        let valLable = "";
        if (triggerType == "计数触发器") {
            valLable = "记录数";
            $(".repeat-interval").css("display", "block");
        }
        else if (triggerType == "周期性触发器") {
            valLable = "时间间隔(毫秒)";
            $(".repeat-interval").css("display", "none");
        }
        else if (triggerType == "特定秒数后停止触发器") {
            valLable = "停止秒数(指定秒数后停止)";
            $(".repeat-interval").css("display", "block");
        }
        //id=triggerVal前一个元素的html=valLable
        $("#triggerVal").prev().html(valLable);
    }

    // 确认计算方式按钮点击事件
    function onClickConfirmCalculation() {
        const calcModal = bootstrap.Modal.getInstance(document.getElementById('calculationModal'));
        //使用jquery语法获得选中值
        let calType = $('input[name="calculationType"]:checked').val();
        let grpType = $('input[name="grpType"]:checked').val();
        let triggerType = $('input[name="triggerType"]:checked').val();

        // 根据条件切换显示内容
        if (grpType === '区域' && calType === '全局窗口' && triggerType === '计数触发器') {
            document.getElementById('flinkOutput').style.display = 'none';
            document.getElementById('echartOutput').style.display = 'block';
            initEchart();
            initStats();
        } else {
            document.getElementById('flinkOutput').style.display = 'block';
            document.getElementById('echartOutput').style.display = 'none';
            document.querySelector('#zoneStats').style.display = 'none';
        }

        let params = {
            calType: calType,
            grpType: grpType,
        };

        if (calType === '滑动窗口') {
            params.winLen = document.getElementById('winLen').value;
            params.winInterval = document.getElementById('winInterval').value;
        }
        else if (calType === '滚动窗口' || calType == '滚动事件时间窗口') {
            params.winLen = document.getElementById('winLenTumbing').value;
        }
        else if (calType === '全局窗口') {
            params.triggerType = $('input[name="triggerType"]:checked').val();
            params.triggerVal = document.getElementById('triggerVal').value;
            if (params.triggerType != '周期性触发器') {
                params.repeatInterval = document.getElementById('repeatInterval').value;
            }
        }

        calcModal.hide();

        // 调用runTask并传递参数
        runTask(FLINK_TEST_FROMMQTT_PARTITION, function () {
            document.getElementById("startMqttSinkBtn").disabled = true;
            document.getElementById("stopMqttSinkBtn").disabled = false;
        }, params);
    }


    // 清除消息功能
    function onClickClearMessages() {
        document.getElementById('wsMessages').innerHTML = '';
        document.getElementById('flinkOutput').innerHTML = '';
    }

    // 初始化WebSocket连接和心跳定时器
    $(document).ready(function () {
        initWebSocket();
        setButtonStatus();
    });

    // 初始化echarts图表
    function initEchart() {
        const chartDom = document.getElementById('echartOutput');
        if (window.echartInstance) {
            window.echartInstance.dispose();
            window.echartInstance = null;
        }
        window.echartInstance = echarts.init(chartDom);
        const option = {
            title: {
                text: '各地区订单数量统计'
            },
            grid: {
                top: '10%',    // 图表顶部留出 20% 的空间，避免与 legend 重叠
                bottom: '10%', // 底部留出 15% 的空间
                left: '5%',   // 左侧留出 10% 的空间
                right: '10%',  // 右侧留出 10% 的空间
            },
            tooltip: {},
            legend: {
                data: [],
                orient: 'vertical',
                right: 10,
                top: 'center'
            },
            xAxis: {
                type: 'category',
                data: []
            },
            yAxis: {
                type: 'value'
            },
            series: []
        };
        window.echartInstance.setOption(option);
    }

    function initStats() {
        document.querySelector('#zoneStats').style.display = 'block';
        document.querySelector('#zoneStats .zone-stats-grid').innerHTML = '';
        document.getElementById("totalCount").value = 0;

    }

    // 更新echarts图表数据
    function updateEchart(data) {
        if (!window.echartInstance) {
            initEchart();
        }

        const option = window.echartInstance.getOption();
        let xDataArr = option.xAxis[0].data;
        let legendArr = option.legend[0].data;

        // 动态确定系列名称
        const seriesName = data.zoneName;
        let seriesIndex = -1;

        // 查找对应的系列
        option.series.forEach((series, index) => {
            if (series.name === seriesName) {
                seriesIndex = index;
            }
        });

        // 如果系列不存在则创建
        if (seriesIndex === -1) {
            seriesIndex = option.series.length;
            option.series.push({
                name: seriesName,
                type: 'line',
                data: [data.count],
                smooth: true
            });
            legendArr.push(seriesName);
        }
        else {
            let sDtate = option.series[seriesIndex].data;
            sDtate.push(data.count);
        }

        let sDataArr = option.series[seriesIndex].data;

        //修改xAxis.data

        let time = new Date();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        let formattedTime = `${hours}:${minutes}:${seconds}`;
        xDataArr.push(formattedTime);

        // xDataArr,legendArr,sDataArr 都只保留最近的10条数据
        while (xDataArr.length > 10) {
            xDataArr.shift();
        }
        while (legendArr.length > 6) {
            legendArr.shift();
        }
        while (sDataArr.length > 10) {
            sDataArr.shift();
        }
        //移除 option.series中name不再 legendArr中的
        for (let i = option.series.length - 1; i >= 0; i--) {
            if (!legendArr.includes(option.series[i].name)) {
                option.series.splice(i, 1);
            }
        }
        window.echartInstance.setOption(option);
    }

    // 更新区域统计显示
    function updateZoneStats(data) {
        const statsContainer = document.querySelector('#zoneStats .zone-stats-grid');
        //查找statsContainer下所有class=zone-stats-child 且data-zone=data.zoneName  的div
        const zoneDiv = statsContainer.querySelector(`.zone-stats-child[data-zone="${data.zoneName}"]`);
        if (zoneDiv) {
            // 更新统计数据
            zoneDiv.setAttribute('data-count', data.count);
            zoneDiv.innerHTML = `<p class='zone-title'>${data.zoneName}</p><p class='zone-count'>${data.count}</p>`;
        }
        else { // 如果不存在，则创建新的div并添加到容器中
            const newZoneDiv = document.createElement('div');
            newZoneDiv.className = 'zone-stats-child';
            newZoneDiv.setAttribute('data-zone', data.zoneName);
            newZoneDiv.setAttribute('data-count', data.count);
            newZoneDiv.innerHTML = `<p class='zone-title'>${data.zoneName}</p><p class='zone-count'>${data.count}</p>`;
            statsContainer.appendChild(newZoneDiv);
        }
        // 更新总计
        const totalCountInput = document.getElementById('totalCount');
        //汇总statsContainer下所有child的data-count
        let totalCount = 0;
        statsContainer.querySelectorAll('.zone-stats-child').forEach(function (div) {
            totalCount += parseInt(div.dataset.count);
        });
        totalCountInput.value = totalCount;
        // 显示统计区域
        document.getElementById('zoneStats').style.display = 'block';
    }

    window.addEventListener("unload", function (event) {
        if (window.torder.websocketHeartbeatInterval) {
            clearInterval(window.torder.websocketHeartbeatInterval);
            console.log('已清理心跳定时器');
        }
        if (window.torder.websocket) {
            window.torder.websocket.close();
            console.log('已关闭WebSocket连接');
        }
        if (window.echartInstance) {
            window.echartInstance.dispose();
            window.echartInstance = null;
        }
        stopWebSocketSink();
    });
</script>

</html>